package com.huirui.server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.context.UserContext;
import com.huirui.server.mapper.ProductFavoriteMapper;
import com.huirui.server.pojo.entity.ProductFavorite;
import com.huirui.server.pojo.result.PageResult;
import com.huirui.server.pojo.vo.ProductBriefInfoVo;
import com.huirui.server.service.ProductFavoriteService;
import com.huirui.server.service.ProductService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yujun
 * @description 针对表【t_user_product_favorite(用户-商品收藏关联表)】的数据库操作Service实现
 * @createDate 2025-09-19 17:07:24
 */
@Service
@Slf4j
public class ProductFavoriteServiceImpl extends ServiceImpl<ProductFavoriteMapper, ProductFavorite>
        implements ProductFavoriteService {

    @Resource
    private ProductService productService;

    @Override
    public List<ProductBriefInfoVo> listUserFavoriteProduct() {
        List<Long> productIdList = lambdaQuery()
                .select(ProductFavorite::getProductId)
                .eq(ProductFavorite::getUserId, UserContext.getId())
                .orderByDesc(ProductFavorite::getFavoriteTime)
                .orderByDesc(ProductFavorite::getProductId)
                .list()
                .stream().map(ProductFavorite::getProductId).toList();
        return productService.listProductBriefInfoVoByIds(productIdList);
    }

    @Override
    public PageResult<ProductBriefInfoVo> listProductFavoriteProduct(Long page, Long pageSize) {
        IPage<ProductFavorite> iPage = new Page<>(page, pageSize);
        lambdaQuery()
                .select(ProductFavorite::getProductId)
                .eq(ProductFavorite::getUserId, UserContext.getId())
                .orderByDesc(ProductFavorite::getFavoriteTime)
                .orderByDesc(ProductFavorite::getProductId)
                .page(iPage);
        List<Long> productIdList = iPage.getRecords().stream().map(ProductFavorite::getProductId).toList();
        List<ProductBriefInfoVo> productBriefInfoVos = productService.listProductBriefInfoVoByIds(productIdList);
        PageResult<ProductBriefInfoVo> pageResult = new PageResult<>();
        pageResult.setTotal(iPage.getTotal());
        pageResult.setRecords(productBriefInfoVos);
        pageResult.setSize(iPage.getSize());
        pageResult.setCurrent(iPage.getCurrent());
        pageResult.setPages(iPage.getPages());
        return pageResult;
    }
}




